<?php

// +---------------------------------------------+
// |     Copyright  2010 - 2018 InterPhoto       |
// |     http://www.weentech.com                 |
// |     This file may not be redistributed.     |
// +---------------------------------------------+


if(!defined('INTERPHOTO')) die('File not found!');



// ##############################################################

function DisplayDate($timestamp, $dateformat = 'Y-m-d H:i:s')
{
	global $mainsettings;

	if(!strlen($dateformat))
	{
		$dateformat = $mainsettings['siteDateFormat'];
	}

	$timezoneoffset = ForceInt($mainsettings['siteTimezone']);

	return $timestamp ?  @gmdate($dateformat, $timestamp + (3600 * $timezoneoffset)) : '';
}

// ##############################################################

function DisplayFilesize($filesize)
{

	$kb = 1024;         // Kilobyte
	$mb = 1048576;      // Megabyte

	if($filesize < $kb)
	{
		$size = $filesize . ' B';
	}
	else if($filesize < $mb)
	{
		$size = round($filesize/$kb,2) . ' K';
	}
	else
	{
		$size = round($filesize/$mb,2) . ' M';
	}

	return (isset($size) AND $size != '0 B' AND  $size != ' B') ? $size : 0;
}

// ##############################################################

function Iif($expression, $returntrue, $returnfalse = '')
{
	if($expression)
	{
		return $returntrue;
	}
	else
	{
		return $returnfalse;
	}
}

// ##############################################################

function SafeSql($source)
{
	$entities_match = array(',',';','$','!','@','#','%','^','&','*','_','(',')','{','}','|',':','"','<','>','?','[',']','\\',"'",'.','/','*','+','~','`','=');
	return str_replace($entities_match, '', trim($source));
}

// ##############################################################

function SafeSearchSql($source)
{
	$entities_match = array('$','!','@','#','%','^','&','*','_','(',')','{','}','|',':','"','<','>','?','[',']','\\',"'",'.','/','*','~','`','=');
	return str_replace($entities_match, '', trim($source));
}


// ##############################################################

function IsEmail($email)
{
	return preg_match("/^[a-z0-9]+[.a-z0-9_-]*@[a-z0-9]+[.a-z0-9_-]*\.[a-z0-9]+$/i", $email);
}

// ##############################################################

function IsName($name)
{
	$entities_match = array(',',';','$','!','@','#','%','^','&','*','_','(',')','{','}','|',':','"','<','>','?','[',']','\\',"'",'/','*','+','~','`','=');
	for ($i = 0; $i<count($entities_match); $i++) {
	     if(strpos($name, $entities_match[$i])){
               return false;
		 }
	}
   return true;
}

// ##############################################################

function IsPass($pass)
{
   return preg_match("/^[[:alnum:]]+$/i", $pass);
}

// ##############################################################

function PassGen($length = 8)
{
	$str = 'abcdefghijkmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	for ($i = 0, $passwd = ''; $i < $length; $i++)
		$passwd .= substr($str, mt_rand(0, strlen($str) - 1), 1);
	return $passwd;
}

// ##############################################################

function IsGet($VariableName) {
	if (isset($_GET[$VariableName])) {
		return true;
	} else {
		return false;
	}

}

// ##############################################################

function IsPost($VariableName) {
	if (isset($_POST[$VariableName])) {
		return true;
	} else {
		return false;
	}

}

// ##############################################################

function ForceIncomingString($VariableName, $DefaultValue = '') {
	if (isset($_GET[$VariableName])) {
		return ForceString($_GET[$VariableName], $DefaultValue);
	} elseif (isset($_POST[$VariableName])) {
		return ForceString($_POST[$VariableName], $DefaultValue);
	} else {
		return $DefaultValue;
	}
}

// ##############################################################

function ForceIncomingInt($VariableName, $DefaultValue = 0) {
	if (isset($_GET[$VariableName])) {
		return ForceInt($_GET[$VariableName], $DefaultValue);
	} elseif (isset($_POST[$VariableName])) {
		return ForceInt($_POST[$VariableName], $DefaultValue);
	} else {
		return $DefaultValue;
	}

}

// ##############################################################

function ForceIncomingCookie($VariableName, $DefaultValue = '') {
	if (isset($_COOKIE[$VariableName])) {
		return ForceString($_COOKIE[$VariableName], $DefaultValue);
	} else {
		return $DefaultValue;
	}
}

// ##############################################################

function ForceIncomingArray($VariableName, $DefaultValue = array()) {
	if (isset($_GET[$VariableName])) {
		return ForceArray($_GET[$VariableName], $DefaultValue);
	} elseif (isset($_POST[$VariableName])) {
		return ForceArray($_POST[$VariableName], $DefaultValue);
	} else {
		return $DefaultValue;
	}
}

// ##############################################################

function ForceBool($InValue, $DefaultBool = 0) {
	if (!$InValue) return $DefaultBool;
	$InValue = strtoupper($InValue);
	if ($InValue == 1) {
		return 1;
	} elseif ($InValue === 0) {
		return 0;
	} elseif ($InValue == 'Y') {
		return 1;
	} elseif ($InValue == 'N') {
		return 0;
	} elseif ($InValue == 'ON') {
		return 1;
	} elseif ($InValue == 'OFF') {
		return 0;
	} elseif ($InValue == 'TRUE') {
		return 1;
	} elseif ($InValue == 'FALSE') {
		return 0;
	} else {
		return $DefaultBool;
	}
}

// ##############################################################

function FlipBool($Bool) {
	$Bool = ForceBool($Bool, 0);
	return $Bool?0:1;
}

// ##############################################################

function EscapeSql($query_string) {
	$conn=mysqli_connect('localhost','root','');
	if (get_magic_quotes_gpc()) {
		$query_string = stripslashes($query_string);
	}

	$query_string = htmlspecialchars(str_replace ('\0', '', $query_string), ENT_QUOTES);
	
	if(function_exists('mysqli_real_escape_string')) {
		$query_string = mysqli_real_escape_string($conn,$query_string);
	}else if(function_exists('mysql_escape_string')){
		$query_string = mysqli_escape_string($query_string);
	}else{
		$query_string = addslashes($query_string);
	}

	return $query_string;
}

// ##############################################################

function Html($String) {
	 return str_replace(array('&amp;','&#039;','&quot;','&lt;','&gt;'), array('&','\'','"','<','>'), $String);
}

// ##############################################################

function ForceInt($InValue, $DefaultValue = 0) {
	$iReturn = intval($InValue);
	return ($iReturn == 0) ? $DefaultValue : $iReturn;
}

// ##############################################################

function ForceString($InValue, $DefaultValue = '') {
	if (is_string($InValue)) {
		$sReturn = EscapeSql(trim($InValue));
		if (empty($sReturn) && strlen($sReturn) == 0) $sReturn = $DefaultValue;
	} else {
		$sReturn = EscapeSql($DefaultValue);
	}
	return $sReturn;
}

// ##############################################################

function ForceArray($InValue, $DefaultValue = array()) {
	if(is_array($InValue)) {
		$aReturn = $InValue;
	} else {
		// assume it's a string
		$sReturn = trim($InValue);
		$length = strlen($sReturn);
		if (empty($length) && strlen($sReturn) == 0) {
			$aReturn = $DefaultValue;
		} else {
			$aReturn = array($sReturn);
		}
	}
	return $aReturn;
}

// ##############################################################

function ShortTitle($string, $length=81)
{
	if(strlen($string) == 0){
		return '';
	}

	if(strlen($string) <= $length) {
		return $string;
	}

	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
	$strcut = '';

	$n = $tn = $noc = 0;
	while($n < strlen($string)) {

		$t = ord($string[$n]);
		if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
			$tn = 1; $n++; $noc++;
		} elseif(194 <= $t && $t <= 223) {
			$tn = 2; $n += 2; $noc += 2;
		} elseif(224 <= $t && $t < 239) {
			$tn = 3; $n += 3; $noc += 2;
		} elseif(240 <= $t && $t <= 247) {
			$tn = 4; $n += 4; $noc += 2;
		} elseif(248 <= $t && $t <= 251) {
			$tn = 5; $n += 5; $noc += 2;
		} elseif($t == 252 || $t == 253) {
			$tn = 6; $n += 6; $noc += 2;
		} else {
			$n++;
		}

		if($noc >= $length) {
			break;
		}
	}

	if($noc > $length) {
		$n -= $tn;
	}

	$strcut = substr($string, 0, $n);

	$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

	return $strcut.'...';
}


// ##############################################################

function GetLangs($filename = 0) {
	$Languages = array();
	$LangPath = BASEPATH . 'languages/';
	$FolderHandle = @opendir($LangPath);
	while (false !== ($Item = readdir($FolderHandle))) {
		if (filesize($LangPath.$Item) && $Item != '.' 	&& $Item != '..' && substr($Item, -4) == '.php') {
			if (substr($Item, 0, 1) != ".") {
				$Languages[] = Iif($filename, $Item, substr($Item, 0, -4));
			}
		}
	}
	@closedir($LangPath);
	return $Languages;
}

// ##############################################################

function GetTemps() {
	$Templates = array();
	$TempPath = BASEPATH . 'templates/';
	$FolderHandle = @opendir($TempPath);
	while (false !== ($Item = readdir($FolderHandle))) {
		if (is_dir($TempPath.$Item) && $Item != '.' 	&& $Item != '..') {
			if (substr($Item, 0, 1) != ".") $Templates[] = $Item;
		}
	}
	@closedir($LangPath);
	return $Templates;
}

// ##############################################################

function DeleteImageById ($imageid, $userid = 0) {
	global $DB;

	if($userid){
		$useridsql = " userid = '$userid' AND ";
	}

	$getfilename = $DB->query_first("SELECT path, filename FROM " . TABLE_PREFIX . "images WHERE ".$useridsql." imageid = '$imageid' ");

	$DB->query("DELETE FROM " . TABLE_PREFIX . "images WHERE ".$useridsql." imageid = '$imageid' ");

	$DB->query("DELETE FROM " . TABLE_PREFIX . "comments WHERE imageid = '$imageid' ");

	@unlink(BASEPATH.'MyWebsiteImages/'.$getfilename['path'].'_'.WEBSITE_KEY .'/original/'.$getfilename['filename']);
	@unlink(BASEPATH.'MyWebsiteImages/'.$getfilename['path'].'_'.WEBSITE_KEY .'/760x760/'.$getfilename['filename']);
	@unlink(BASEPATH.'MyWebsiteImages/'.$getfilename['path'].'_'.WEBSITE_KEY .'/160x160/'.$getfilename['filename']);
	@unlink(BASEPATH.'MyWebsiteImages/'.$getfilename['path'].'_'.WEBSITE_KEY .'/80x80/'.$getfilename['filename']);
	@unlink(BASEPATH.'MyWebsiteImages/'.$getfilename['path'].'_'.WEBSITE_KEY .'/32x32/'.$getfilename['filename']);

}

// ###############################################################

function InterEncode($title) {
	return base64_encode($title);
}


// ###############################################################

function IsUploadedFile($file) {
	return function_exists('is_uploaded_file') && (is_uploaded_file($file) || is_uploaded_file(str_replace('\\\\', '\\', $file)));
}


// ###############################################################

function ForceDir($str) {
	return preg_match("/^[a-zA-Z0-9]+[a-zA-Z0-9_\.]+[a-zA-Z0-9]+$/i", $str)? $str : '';
}

// ###############################################################

function GetIP() {
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$thisip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$thisip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$thisip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$thisip = $_SERVER['REMOTE_ADDR'];
	}

	preg_match("/[\d\.]{7,15}/", $thisip, $thisips);
	$thisip = $thisips[0] ? $thisips[0] : 'unknown';
	return $thisip;
}

?>